//
//  MyTradeConfirmViewController.m
//  SocietySale
//
//  Created by Mike on 16/11/14.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "MyTradeConfirmViewController.h"
#import "MyTradeConfirmTableVC.h"
#import "MSTradeSuccessViewController.h"

@interface MyTradeConfirmViewController ()<UIGestureRecognizerDelegate,UITextFieldDelegate>
@property (nonatomic, strong) UILabel     *payLabel;
@property (nonatomic, strong) GXButton    *doneBtn;
@property (nonatomic, strong) MyTradeConfirmTableVC *tableVC;
@property (nonatomic, strong) NSArray    *placeHoderArray;
@property (nonatomic, strong) NSString   *areaPhonePrefix;
@property (nonatomic, strong) NSString   *areaPhoneSuffix;
@property (nonatomic, assign) BOOL       isAreaPhoneNum;
@property (nonatomic, assign) NSInteger  coinCount;
@end

@implementation MyTradeConfirmViewController

- (void)dealloc
{
    for(UIView* view in [self.contentView subviews])
    {
        [view removeFromSuperview];
    }
    
    self.contentView=nil;
    self.VctrID=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:@"" forKey:@"phoneState"];
    [ud synchronize];
}

- (void)initNavigationBar{
    [super initNavigationBar];
    titleLable.text = @"交易确认";
    leftBarBtn.hidden = NO;
    //    rightBarBtn.hidden = YES;
}

- (void)initUI{
    self.tableVC = [[MyTradeConfirmTableVC alloc] initWithStyle:UITableViewStylePlain];
    self.tableVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.contentView.height);
    self.tableVC.enableRefresh = NO;
    self.tableVC.enableRequest = NO;
    self.tableVC.delegate = (id)self;
    self.tableVC.tradeType = self.tradeType;
    self.tableVC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.tableVC.view];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 135)];
    footerView.backgroundColor = kDefaultViewBackgroundColor;
    self.tableVC.tableView.tableFooterView = footerView;
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    bgView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:bgView];
    
    _payLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH, 50)];
    _payLabel.font = HeitiFont(13);
    _payLabel.textColor = kLightBlackColor;
    [bgView addSubview:_payLabel];
    
    [self setPriceWithTradeModel:_model];
    
    self.doneBtn = [[GXButton alloc] initWithFrame:CGRectMake(12, 70, SCREEN_WIDTH-24, 45)];
    self.doneBtn.titleLabel.font = HeitiFont(16);
    [self.doneBtn setTitle:@"确认并提交" forState:UIControlStateNormal];
    [self.doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.doneBtn.backgroundColor = kBlueColor;
    self.doneBtn.layer.cornerRadius = 2;
    [self.doneBtn addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:self.doneBtn];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    [self.contentView addGestureRecognizer:tapGesture];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShownLogin:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiddenLogin:) name:UIKeyboardWillHideNotification object:nil];
    
    _isAreaPhoneNum = NO;
    _areaPhonePrefix = @"";
    _areaPhoneSuffix = @"";
    _coinCount = 0;
    
    [netEngine requestTradeDetailWithTarget:self.VctrID hudView:self.contentView tradeId:_model.itemId];
}

- (void)testDataFunc{
    /*
    MSTradeModel *model = [[MSTradeModel alloc] init];
    model.title = @"上海浦东世和空港中心商业住房项目";
    model.projectType = @"求购业主联系人信息";
    model.tradeState = @"交易中";
    model.tradeNum = @"3次交易";
    model.name = @"周世鹏";
    model.position = @"经理";
    model.phone = @"13384789442";
    model.theme = @"项目主题    电缆附件招标最新进展";
    model.content = @"内容   杭州地铁二号线目前极影施工阶段";
    model.tradeEvaluate = @"评价   4颗星";
    model.tradePrice = @"12";
    model.memberType = @"[匿名会员]";
    model.memberLevel = @"2钻会员";
    model.time = @"2016.9.15";
    model.type = @"2";
    model.typeGroup = @"progress";//progress   contacts
    */
    
    self.tableVC.model = _model;
    if ([_model.type isEqualToString:@"1"]) {
        self.tradeType = TradeType_Sale;
    }
    if ([_model.type isEqualToString:@"2"] && [_model.typeGroup isEqualToString:@"progress"]) {
        self.tradeType = TradeType_StagePurchase;
    }
    
    MSDetailContactModel *contactModel = [[MSDetailContactModel alloc] init];
//    contactModel.name = @"周长生";
//    contactModel.position = @"项目经理";
//    contactModel.company = @"上海电力有限公司";
//    contactModel.telephone = @"187****6786";
//    contactModel.address = @"上海市宝山区友谊路89号";
//    contactModel.source = @"平台采集";
//    contactModel.time = @"08.13";
//    contactModel.otherProject = @"格瑞特个人土豪";
    
    if ([_model.type isEqualToString:@"2"] && [_model.typeGroup isEqualToString:@"contacts"]) {
        self.tradeType = TradeType_ContactsPurchase;
        self.tableVC.contactArray = [NSMutableArray arrayWithArray
                                     :@[
                                        [DOKeyValue key:@"姓名" value:[HDUtil check:_model.name] placeHolder:@"请填写"],
                                        [DOKeyValue key:@"公司" value:[HDUtil check:contactModel.company] placeHolder:@"请填写"],
                                        [DOKeyValue key:@"职位" value:[HDUtil check:contactModel.position] placeHolder:@"请填写"],
                                        [DOKeyValue key:@"电话" value:[HDUtil check:contactModel.telephone] placeHolder:@"请输入手机号"],
                                        [DOKeyValue key:@"地址" value:[HDUtil check:contactModel.address] placeHolder:@"请填写"],
                                        [DOKeyValue key:@"备注" value:[HDUtil check:contactModel.otherProject] placeHolder:@"可选填写"]
                                        ]];
        
        _placeHoderArray = @[@"请填写姓名",@"请填写公司名",@"请填写职位",@"请填写电话",@"请填写地址",@"请填写备注"];
    }
}

- (void)updateViewController:(NSNotification *)note {
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"TradeDetail"]!=nil){
            MSTradeModel *model = responseDic[@"TradeDetail"];
            
            _coinCount = [model.wallet integerValue];
            [self setPriceWithTradeModel:model];
        }
        if (responseDic[@"SaleTrade"]!=nil){
            self.model.orderId = responseDic[@"orderId"];
            [self tradeSuccess];
        }
        if (responseDic[@"BuyTradeContacts"]!=nil){
            self.model.orderId = responseDic[@"orderId"];
            [self tradeSuccess];
        }
        if (responseDic[@"BuyTradeProject"]!=nil){
            self.model.orderId = responseDic[@"orderId"];
            [self tradeSuccess];
        }
    }
}

- (void)tradeSuccess{
    [HDUtil showMessage:@"交易成功"];
    MSTradeSuccessViewController *vc = [[MSTradeSuccessViewController alloc] init];
    vc.model = self.model;
    [rootNavigation pushViewController:vc animated:YES];
}

- (void)setPriceWithTradeModel:(MSTradeModel*)model{
    NSString *price = @"";
    if ([_model.type isEqualToString:@"2"]){//求购
        price = [NSString stringWithFormat:@"您可获得： %@",model.getPrice];
    }
    else{//出售需支付
        price = [NSString stringWithFormat:@"您需支付： %@",model.getPrice];
    }
    
    NSMutableAttributedString *priceAttstr = [[NSMutableAttributedString alloc] initWithString:price attributes:@{NSFontAttributeName:HeitiFont(15),NSForegroundColorAttributeName:kLightBlackColor}];
    
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
    textAttachment.bounds = CGRectMake(0, -5, 20, 20);
    textAttachment.image = [UIImage imageNamed:@"coin"];
    NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
    [priceAttstr insertAttributedString:attachmentString atIndex:6];
    
    NSAttributedString *symbolStr = [[NSAttributedString alloc] initWithString:@" x " attributes:@{NSFontAttributeName:HeitiFont(13),NSForegroundColorAttributeName:kDarkGrayColor}];
    [priceAttstr insertAttributedString:symbolStr atIndex:7];
    
    if ([_model.type isEqualToString:@"2"]){//求购
        self.payLabel.attributedText = priceAttstr;
    }
    else{//出售需支付
        if ([model.getPrice integerValue]>_coinCount) {//余额不足
            NSAttributedString *suffixStr = [[NSAttributedString alloc] initWithString:@"  !剩余江湖币不足" attributes:@{NSFontAttributeName:HeitiFont(13),NSForegroundColorAttributeName:KRedColor}];
            [priceAttstr appendAttributedString:suffixStr];
        }
        else{
            NSAttributedString *suffixStr = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"        余额%ld",_coinCount] attributes:@{NSFontAttributeName:HeitiFont(13),NSForegroundColorAttributeName:kDarkGrayColor}];
            [priceAttstr appendAttributedString:suffixStr];
        }
        
        self.payLabel.attributedText = priceAttstr;
    }
}

- (void)doneClick{
    if (self.tradeType == TradeType_Sale) {//出售
        [netEngine requestSaleTradeWithTarget:self.VctrID hudView:self.contentView tradeId:_model.itemId params:nil];
    }
    if (self.tradeType == TradeType_StagePurchase) {//购买项目进展
        [self.view endEditing:YES];
        if ([[self.tableVC.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
            //有空格，只输入了空格
            [HDUtil showMessage:@"请填写项目进展"];
            return;
        }
        if ([[self.tableVC.remarkTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
            //有空格，只输入了空格
            [HDUtil showMessage:@"请填写内容描述"];
            return;
        }
        NSDictionary *dict = @{
                               @"name":self.tableVC.textField.text,
                               @"remark":self.tableVC.remarkTextView.text};
        [netEngine requestBuyTradeProjectWithTarget:self.VctrID hudView:self.contentView tradeId:_model.itemId params:dict];
    }
    if (self.tradeType == TradeType_ContactsPurchase){//购买联系人
        [self.view endEditing:YES];
        
        if (_isAreaPhoneNum) {//有区号
            for (int i = 0; i<5; i++) {
                if (i == 3) {// 区号判断
                    if ([[_areaPhonePrefix stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
                        //有空格，只输入了空格
                        [HDUtil showMessage:@"请输入区号"];
                        return;
                    }
                    if ([[_areaPhoneSuffix stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
                        //有空格，只输入了空格
                        [HDUtil showMessage:@"请输入电话号码"];
                        return;
                    }
                }
                else{
                    DOKeyValue *data = self.tableVC.contactArray[i];
                    if ([[data.value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
                        //有空格，只输入了空格
                        [HDUtil showMessage:_placeHoderArray[i]];
                        return;
                    }
                }
            }
        }
        else{
            for (int i = 0; i<5; i++) {
                DOKeyValue *data = self.tableVC.contactArray[i];
                if ([[data.value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
                    //有空格，只输入了空格
                    [HDUtil showMessage:_placeHoderArray[i]];
                    return;
                }
            }
        }
        DOKeyValue *data = self.tableVC.contactArray[0];
        DOKeyValue *data2 = self.tableVC.contactArray[1];
        DOKeyValue *data3 = self.tableVC.contactArray[2];
        DOKeyValue *data4 = self.tableVC.contactArray[3];
        DOKeyValue *data5 = self.tableVC.contactArray[4];
        DOKeyValue *data6 = self.tableVC.contactArray[5];
        
        NSDictionary *dict = @{
                               @"name":data.value,
                               @"address":data2.value,
                               @"mobile":data3.value,
                               @"phone":data4.value,
                               @"position":data5.value,
                               @"remark":data6.value};
        [netEngine requestBuyTradeContactsWithTarget:self.VctrID hudView:self.contentView tradeId:_model.itemId params:dict];
    }
}

- (void)areaPhoneNumEndEditIsArea:(BOOL)isArea prefix:(NSString*)prefixStr suffix:(NSString*)suffixStr{
    _isAreaPhoneNum = isArea;
    _areaPhonePrefix = prefixStr;
    _areaPhoneSuffix = suffixStr;
}

- (void)tapClick{
    [self.view endEditing:YES];
}

//键盘显示的时候的处理
- (void)keyboardWasShownLogin:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    _tableVC.tableView.height = SCREEN_HEIGHT-KNavBarHeight-kbSize.height;
//    [self updateDataArray];
}

//键盘消失的时候的处理
- (void)keyboardWillBeHiddenLogin:(NSNotification*)aNotification
{
    _tableVC.tableView.height = SCREEN_HEIGHT-KNavBarHeight;
}

@end
